<template>
  <div class="system-setting-container">
         <!-- 搜索表单 -->
     <el-card class="search-card">
       
       <el-form :model="searchParams" inline>
         <el-form-item label="配置ID">
           <el-input
             v-model="searchParams.id"
             placeholder="请输入配置ID"
             clearable
             style="width: 200px"
           />
         </el-form-item>
         <el-form-item label="分组名称">
           <el-input
             v-model="searchParams.groupName"
             placeholder="请输入分组名称"
             clearable
             style="width: 200px"
           />
         </el-form-item>
         <el-form-item label="配置键">
           <el-input
             v-model="searchParams.key"
             placeholder="请输入配置键"
             clearable
             style="width: 200px"
           />
         </el-form-item>
                   <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增配置
            </el-button>
          </el-form-item>
       </el-form>
     </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
             <template #header>
         <div class="card-header">
           <span>系统配置列表</span>
         </div>
       </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        stripe
        table-layout="auto"
      >
        <el-table-column prop="id" label="配置ID" min-width="120" show-overflow-tooltip />
        <el-table-column prop="groupName" label="分组名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="key" label="配置键" min-width="180" show-overflow-tooltip />
        <el-table-column prop="value" label="配置值" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="value-cell" @click="handleViewValue(row)">
              <div class="value-preview">
                {{ getValuePreview(row.value) }}
              </div>
              <el-icon class="view-icon"><View /></el-icon>
            </div>
          </template>
        </el-table-column>
                 <el-table-column prop="enable" label="状态" min-width="100">
           <template #default="{ row }">
             <el-switch
               v-model="row.enable"
               :active-value="true"
               :inactive-value="false"
               :loading="row.statusLoading"
               @change="handleStatusChange(row)"
               active-text="启用"
               inactive-text="禁用"
               active-color="#67C23A"
               inactive-color="#F56C6C"
             />
           </template>
         </el-table-column>
        <el-table-column prop="modifyTime" label="修改时间" min-width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.modifyTime) }}
          </template>
        </el-table-column>
                 <el-table-column label="操作" min-width="180" fixed="right">
           <template #default="{ row }">
             <div class="action-buttons">
               <el-button
                 type="primary"
                 size="small"
                 @click="handleEdit(row)"
               >
                 <el-icon><Edit /></el-icon>
                 编辑
               </el-button>
               <el-button
                 type="danger"
                 size="small"
                 @click="handleDelete(row)"
               >
                 <el-icon><Delete /></el-icon>
                 删除
               </el-button>
             </div>
           </template>
         </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
             </div>
     </el-card>

           <!-- 新增配置弹窗 -->
      <el-dialog
        v-model="addDialogVisible"
        title="新增配置"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
                <el-form
           ref="addFormRef"
           :model="addForm"
           :rules="addFormRules"
           label-width="120px"
         >
           <el-form-item label="配置组名称" prop="groupName">
             <el-input
               v-model="addForm.groupName"
               placeholder="请输入配置组名称"
               clearable
             />
           </el-form-item>
           <el-form-item label="描述" prop="description">
             <el-input
               v-model="addForm.description"
               type="textarea"
               :rows="3"
               placeholder="请输入描述（可选）"
               clearable
             />
           </el-form-item>
           <el-form-item label="配置项Key" prop="key">
             <el-input
               v-model="addForm.key"
               placeholder="请输入配置项Key"
               clearable
             />
           </el-form-item>
           <el-form-item label="配置项Value" prop="value">
             <el-input
               v-model="addForm.value"
               type="textarea"
               :rows="4"
               placeholder="请输入配置项Value"
               clearable
             />
           </el-form-item>
           <el-form-item label="是否生效" prop="enable">
             <el-switch
               v-model="addForm.enable"
               active-text="生效"
               inactive-text="不生效"
               active-color="#67C23A"
               inactive-color="#F56C6C"
             />
           </el-form-item>
         </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelAdd">取消</el-button>
            <el-button type="primary" @click="handleConfirmAdd" :loading="addLoading">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 编辑配置弹窗 -->
      <el-dialog
        v-model="editDialogVisible"
        title="编辑配置"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="120px"
        >
          <el-form-item label="配置组名称" prop="groupName">
            <el-input
              v-model="editForm.groupName"
              placeholder="请输入配置组名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="editForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入描述（可选）"
              clearable
            />
          </el-form-item>
          <el-form-item label="配置项Key" prop="key">
            <el-input
              v-model="editForm.key"
              placeholder="请输入配置项Key"
              clearable
            />
          </el-form-item>
          <el-form-item label="配置项Value" prop="value">
            <el-input
              v-model="editForm.value"
              type="textarea"
              :rows="4"
              placeholder="请输入配置项Value"
              clearable
            />
          </el-form-item>
          <el-form-item label="是否生效" prop="enable">
            <el-switch
              v-model="editForm.enable"
              active-text="生效"
              inactive-text="不生效"
              active-color="#67C23A"
              inactive-color="#F56C6C"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelEdit">取消</el-button>
            <el-button type="primary" @click="handleConfirmEdit" :loading="editLoading">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
   </div>
 </template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Edit, View, Plus, Delete } from '@element-plus/icons-vue'
import { 
  getSystemSettingPageApi,
  updateEnableStatusApi,
  saveSettingApi,
  updateSettingApi,
  deleteSettingApi,
  SystemSettingSearchReq, 
  SystemSettingResult,
  SettingDto
} from '@/api/system'

// 扩展SystemSettingResult接口，添加statusLoading属性
interface ExtendedSystemSettingResult extends SystemSettingResult {
  statusLoading?: boolean
}

// 响应式数据
const loading = ref(false)
const tableData = ref<ExtendedSystemSettingResult[]>([])
const totals = ref(0)

// 新增配置相关
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref()

// 编辑配置相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const currentEditId = ref('')

// 新增表单数据
const addForm = reactive<SettingDto>({
  groupName: '',
  description: '',
  key: '',
  value: '',
  enable: false
})

// 编辑表单数据
const editForm = reactive<SettingDto>({
  groupName: '',
  description: '',
  key: '',
  value: '',
  enable: false
})

// 新增表单验证规则
const addFormRules = {
  groupName: [
    { required: true, message: '请输入配置组名称', trigger: 'blur' },
    { min: 1, max: 50, message: '配置组名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  key: [
    { required: true, message: '请输入配置项Key', trigger: 'blur' },
    { min: 1, max: 100, message: '配置项Key长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入配置项Value', trigger: 'blur' }
  ]
}

// 编辑表单验证规则
const editFormRules = {
  groupName: [
    { required: true, message: '请输入配置组名称', trigger: 'blur' },
    { min: 1, max: 50, message: '配置组名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  key: [
    { required: true, message: '请输入配置项Key', trigger: 'blur' },
    { min: 1, max: 100, message: '配置项Key长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入配置项Value', trigger: 'blur' }
  ]
}

// 搜索参数
const searchParams = reactive<SystemSettingSearchReq>({
  id: '',
  groupName: '',
  key: '',
  pageIndex: 1,
  pageSize: 10
})

// 分页参数
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const response = await getSystemSettingPageApi(searchParams)
    // 为每一行数据添加statusLoading属性
    tableData.value = response.data.list.map(item => ({
      ...item,
      statusLoading: false
    }))
    totals.value = response.data.total
  } catch (error) {
    console.error('加载系统配置失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchParams.pageIndex = 1
  pagination.pageIndex = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchParams.id = ''
  searchParams.groupName = ''
  searchParams.key = ''
  searchParams.pageIndex = 1
  pagination.pageIndex = 1
  loadData()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  searchParams.pageSize = size
  pagination.pageSize = size
  searchParams.pageIndex = 1
  pagination.pageIndex = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  searchParams.pageIndex = page
  pagination.pageIndex = page
  loadData()
}

// 编辑配置
const handleEdit = (row: SystemSettingResult) => {
  editDialogVisible.value = true
  currentEditId.value = row.id
  
  // 填充表单数据
  editForm.groupName = row.groupName
  editForm.description = row.description || ''
  editForm.key = row.key
  editForm.value = row.value
  editForm.enable = row.enable || false
  
  // 清除验证
  if (editFormRef.value) {
    editFormRef.value.clearValidate()
  }
}

// 删除配置
const handleDelete = (row: SystemSettingResult) => {
  ElMessageBox.confirm(
    `确定要删除配置 "${row.key}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: false
    }
  ).then(async () => {
    try {
      await deleteSettingApi(row.id)
      ElMessage.success('删除配置成功')
      // 重新加载数据
      await loadData()
    } catch (error) {
      console.error('删除配置失败:', error)
      ElMessage.error('删除配置失败')
    }
  }).catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除')
  })
}

// 新增配置
const handleAdd = () => {
  addDialogVisible.value = true
  // 重置表单
  addForm.groupName = ''
  addForm.description = ''
  addForm.key = ''
  addForm.value = ''
  addForm.enable = false
  // 清除验证
  if (addFormRef.value) {
    addFormRef.value.clearValidate()
  }
}

// 取消新增
const handleCancelAdd = () => {
  addDialogVisible.value = false
}

// 取消编辑
const handleCancelEdit = () => {
  editDialogVisible.value = false
}

// 确认新增
const handleConfirmAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    addLoading.value = true
    
    await saveSettingApi(addForm)
    ElMessage.success('新增配置成功')
    addDialogVisible.value = false
    
    // 重新加载数据
    await loadData()
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('新增配置失败:', error)
      ElMessage.error('新增配置失败')
    }
  } finally {
    addLoading.value = false
  }
}

// 确认编辑
const handleConfirmEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    await updateSettingApi(currentEditId.value, editForm)
    ElMessage.success('编辑配置成功')
    editDialogVisible.value = false
    
    // 重新加载数据
    await loadData()
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('编辑配置失败:', error)
      ElMessage.error('编辑配置失败')
    }
  } finally {
    editLoading.value = false
  }
}

// 处理状态变更
const handleStatusChange = async (row: ExtendedSystemSettingResult) => {
  // 添加loading状态
  row.statusLoading = true
  
  try {
    await updateEnableStatusApi(row.id, row.enable)
    ElMessage.success(`状态更新成功：${row.enable ? '启用' : '禁用'}`)
    // 重新加载数据以获取最新的修改时间
    await loadData()
  } catch (error) {
    // 如果失败，恢复原状态
    row.enable = !row.enable
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
  } finally {
    // 移除loading状态
    row.statusLoading = false
  }
}

// 查看配置值详情
const handleViewValue = (row: SystemSettingResult) => {
  ElMessageBox.alert(
    `<div style="text-align: left; max-height: 400px; overflow-y: auto;">
      <div style="margin-bottom: 10px; font-weight: bold; color: #409EFF;">配置键：${row.key}</div>
      <div style="margin-bottom: 10px; font-weight: bold; color: #409EFF;">分组名称：${row.groupName}</div>
      <div style="margin-bottom: 10px; font-weight: bold; color: #409EFF;">配置值：</div>
      <div style="background: #f5f7fa; padding: 15px; border-radius: 4px; border: 1px solid #e4e7ed; white-space: pre-wrap; word-break: break-all; font-family: 'Courier New', monospace; font-size: 14px; line-height: 1.5;">
        ${row.value}
      </div>
    </div>`,
    '配置值详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'value-detail-dialog'
    }
  )
}

// 获取配置值预览
const getValuePreview = (value: string) => {
  if (!value) return '-'
  // 如果是JSON，尝试格式化
  try {
    const parsed = JSON.parse(value)
    const formatted = JSON.stringify(parsed, null, 2)
    return formatted.length > 100 ? formatted.substring(0, 100) + '...' : formatted
  } catch {
    // 不是JSON，直接截取
    return value.length > 100 ? value.substring(0, 100) + '...' : value
  }
}



// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="less">
.system-setting-container {
  padding: 20px;
  font-size: 16px;
  width: 100%;
  max-width: 100%;
  
           .search-card {
        margin-bottom: 20px;
        
        :deep(.el-form-item__label) {
          font-size: 16px;
          font-weight: 500;
        }
        
        :deep(.el-input__inner) {
          font-size: 16px;
        }
        
        :deep(.el-button) {
          font-size: 16px;
          padding: 12px 20px;
        }
      }
  
  .table-card {
    width: 100%;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: 600;
    }
    
    :deep(.el-table) {
      font-size: 16px;
      width: 100% !important;
      
      .el-table__header {
        th {
          font-size: 16px;
          font-weight: 600;
          padding: 16px 8px;
        }
      }
      
      .el-table__body {
        td {
          font-size: 16px;
          padding: 16px 8px;
        }
      }
      
      .el-table__inner-wrapper {
        width: 100% !important;
      }
      
      .el-table__body-wrapper {
        width: 100% !important;
      }
    }
    
                 .value-cell {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 4px 8px;
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s ease;
          min-height: 28px;
          
          &:hover {
            background: #e3f2fd;
            border-color: #2196f3;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(33, 150, 243, 0.15);
          }
          
          .value-preview {
            flex: 1;
            font-size: 13px;
            line-height: 1.3;
            color: #333;
            word-break: break-all;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            max-height: 36px;
            overflow: hidden;
          }
          
          .view-icon {
            margin-left: 6px;
            color: #409EFF;
            font-size: 14px;
            flex-shrink: 0;
          }
        }
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    
    .el-button {
      margin: 0;
      flex-shrink: 0;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    
    :deep(.el-pagination) {
      font-size: 16px;
      
      .el-pagination__total {
        font-size: 16px;
      }
      
      .el-pagination__sizes {
        .el-select .el-input__inner {
          font-size: 16px;
        }
      }
      
      .btn-prev, .btn-next {
        font-size: 16px;
      }
      
      .el-pager li {
        font-size: 16px;
      }
    }
  }
}

// 全局样式，用于配置值详情弹窗
:global(.value-detail-dialog) {
  .el-message-box__content {
    max-width: 700px;
    min-width: 500px;
  }
  
  .el-message-box__message {
    padding: 0;
  }
  
  .el-message-box__header {
    padding: 20px 20px 10px;
  }
  
     .el-message-box__body {
     padding: 10px 20px 20px;
   }
 }

// 新增配置弹窗样式
.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}
</style>